var express = require('express');
var router = express.Router();
var qs = require('querystring');
var myUtil = require('../utils/myUtil.js');
var dataChecker = require('../utils/dataChecker.js');
var dbUtil = require("../utils/dbUtil.js");

// 
router.post("/", function(req, res) {
	var body = "";
	req.on("data", function(chunk) {
		body += chunk;
	});

	req.on('end', function() {
		var json = parseInput(body);
		if (!json.data) {
			res.send(JSON.stringify(json));
			return;
		}

		//
		verifyUser(json.data.user, function(isOk, errMsg) {
			var result;
			if (!isOk) {
				console.log('bind: verifyUser wrong');
				result = myUtil.resJsonErr(errMsg);
				res.send(JSON.stringify(result));
				return;
			}

			// update table: device
			console.log('bind: verifyUser ok');
			dbUtil.bindDeviceUser(req.db, json.data, function(isOk, errMsg) {
				if (!isOk) {
					console.log('bind: db operation failed');
					result = myUtil.resJsonErr(errMsg);
				} else {
					console.log('bind: db operation ok');
					result = myUtil.resJsonOk(null);
				}
				res.send(JSON.stringify(result));
			});
		});
	});
});

var template = {
	"deviceUuid": "xxx",
	"user": {
		"id": "xxx",
		"password": "xxx"
	}
};

function parseInput(data) {
	var json = myUtil.str2Json(data);
	if (!json) {
		return myUtil.resJsonErr("canot parse to json");
	}

	var checkResult = dataChecker.check(template, json);
	if (checkResult.isOk === false) {
		return myUtil.resJsonErr(checkResult.msg);
	}

	return myUtil.resJsonOk(json);
}

function verifyUser(user, callback) {
	var url = "http://localhost:8080/user/auth";
	// var url = "http://172.16.1.43:8080/user/auth";
	myUtil.makePost(url, JSON.stringify(user), function(error, res) {
		if (error) {
			console.log("bind:verifyUser error");
		} else {
			console.log(res);
			var json = myUtil.str2Json(res);
			if (!json) {
				callback(false, "verifyUser: res cannot parse to json");
			} else if (json.status === "ok") {
				callback(true, null);
			} else {
				callback(false, json.description);
			}
		}
	});
}

module.exports = router;